package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.ClassMapper;
import com.itheima.pojo.Class1;
import com.itheima.pojo.ClassAddReq;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
public class ClassServiceImpl implements ClassService {
    @Autowired
    private ClassMapper classMapper;

    @Override
    public Boolean addClass(Class1 cls) {
        try {
            classMapper.insert(cls);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(String[] ids) throws Exception {
        try {
            classMapper.deleteByIds(ids);
            return true;
        }catch (Exception e){
            // 返回值不为true即可在controller层返回Result.error("")
            throw new Exception();
        }
    }

    @Override
    public PageBean getAllClass(Integer page, Integer pageSize, String className, LocalDate beginTime, LocalDate endTime) {
        PageHelper.startPage(page, pageSize);

        // 查询返回的所有班级信息
        List<Class1> list = classMapper.list(className, beginTime, endTime);
        // 返回前端的时PageBean，这个Bean的rows封装的是ClassReq对象
        // 创建ClassReq
        List<ClassAddReq> response = new ArrayList<>();
        list.forEach(e -> {
            Emp emp = new Emp();
            emp.setId(e.getHeadTeacher());
//            emp.setName(e);
            ClassAddReq one = new ClassAddReq(emp, e.getId(), e.getClassName(), e.getRoomName(), e.getStartTime(), e.getEndTime(),
                    e.getCreateTime(), e.getUpdateTime());
            response.add(one);
        });
        PageInfo<ClassAddReq> pageInfo = new PageInfo<>(response);
        PageBean pageBean = new PageBean(pageInfo.getTotal(), pageInfo.getList());
        return pageBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateClass(Class1 cls) throws Exception{
        try {
            classMapper.updateClass(cls);
            return true;
        }catch (Exception e){
            // 返回值不为true即可在controller层返回Result.error("")
            throw new Exception();
        }
    }
}
